package com.app.Activity;

import it.unipr.ce.dsg.s2p.sip.Address;

import java.util.ArrayList;

import com.app.Controller.ActivityController;
import com.app.Controller.NetworkController;
import com.app.DTO.AccountDTO;
import com.app.Network.NetworkLayer;
import com.app.PhanQuyen.Quyen;

import android.accounts.Account;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import app.com.ModuleRole.R;

public class trucActivity extends Activity {
	
	public static ArrayList<Integer> yesVote;
	public static ArrayList<Integer> noVote;
	
	public static Runnable showMessage;
	public static Runnable showChatMessage;
	public static Runnable dislayKickMember;
	public static Runnable showForm1;
	public static Runnable showResultVoteKick;
	public static Runnable finishAct; 
	public  int timeVoteKick;
	int timeStopTalk;
	public static String message;
	public static String address;//dia chi cua nguoi ban chat rieng voi minh 
	public static String chatMessage;
	
	public static Address ipBeingKick;
	public static Address ipBeingStopTalk;
	
	public static int kickVoteResult;
	public  ArrayList<Quyen> quyen=null;
	public  AccountDTO account=null;
	public EditText listChat;
	public EditText txtContent;
	
	int port=8080;  
	
	
	private AlertDialog.Builder _builder;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dung_noi_chuyen);
		Log.d("Phu","Vao oncreate");
		listChat=(EditText)findViewById(R.id.txtListMessage);

		Button btnShow=(Button)findViewById(R.id.btnShowMess);
		btnShow.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				message="hello";
				NetworkController.ShowMessageNotice(message);
			}
		});
		showMessage=new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
			Show(message);	
			}
		};
		showChatMessage=new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				CapNhatListChat(chatMessage,address);
			}
		};
		dislayKickMember=new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
			HienThiMHBieuQuyetKick();	
			}
		};
		showResultVoteKick=new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
			
				ShowResultVoteKick(ipBeingKick);
			}
		};
		
		finishAct=new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				finishActivity();
			}
		};
		//tao lao
		showForm1=new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				showFrm1();
			}
		};
		//end tao lao
		
		Button btnStopTalking=(Button)findViewById(R.id.btnStopTalking);
		btnStopTalking.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				ShowSetTimeStopTalking();
				
				
			}
		});
		
		Button btnAcceptTalking=(Button)findViewById(R.id.btnContinouTalking);
		btnAcceptTalking.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				NetworkController.GuiChoPhepNoiChuyen(new Address("TRUC@192.168.1.77:"+port));
				Log.d("Phu","vao onclick cho noi");
			}
		});
		
		txtContent=(EditText)findViewById(R.id.txtMessage);
		
		Button btnSendMessage=(Button)findViewById(R.id.btnSendMessage);
		btnSendMessage.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				NetworkController.GuiTinNhanChat(new Address("TRUC@192.168.1.77:"+port), txtContent.getText().toString());
				Log.d("Phu","vao onclick gui tin");
				txtContent.setText("");
			}
		});
		
		
		Button btnKick=(Button)findViewById(R.id.btnKickMember);
		btnKick.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				ShowSetTimeVoteKick();
			}
		});
		
		Button btnThongKe=(Button)findViewById(R.id.btnThongKe);
		btnThongKe.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				NetworkController.DislayResultVoteKick();
			}
		});
		
		//tao lao
		
		Button btnTest=(Button)findViewById(R.id.btnTest);
		btnTest.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				NetworkController.ShowForm1();
			}
		});
	}
	
	public void ShowSetTimeVoteKick(){
		final EditText txtTime=new EditText(this);
		txtTime.setSingleLine();
		txtTime.setInputType(2);
		AlertDialog dlg= new AlertDialog.Builder(this)
		.setTitle("Chọn thời gian biểu quyết")
		.setMessage("Thời gian được tính bằng giây.")
		.setView(txtTime)
		.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				String StrTime=txtTime.getText().toString();
				int time=Integer.parseInt(StrTime);
				timeVoteKick=time;
				yesVote=new ArrayList<Integer>();
				noVote=new ArrayList<Integer>();
				ipBeingKick=new Address("TRUC@192.168.1.88:8080");
				NetworkController.SendVoteKickMember(new Address("TRUC@192.168.1.88:8080"), ipBeingKick,time);
				NetworkController.SendVoteKickMember(new Address("TRUC@192.168.1.99:8080"), ipBeingKick,time);
			//	NetworkController.SendVoteKickMember(new Address("TRUC@192.168.1.77:8080"), ipBeingKick,time);
				Log.d("Phu","Da gui xong kick");
				//dem thoi gian
				long kickTime=timeVoteKick*1000;
				
				CountDownTimer timer = new CountDownTimer(kickTime,1000) {
				@Override
				public void onTick(long millisUntilFinished) {
					
					Thread bg =  new Thread(new Runnable() {
						@Override
						public void run() {
							try {
							
							}
							catch (Throwable t) {
								Log.d("PEERDROID","Loi Login " + t.getMessage());
							}
						}
					});
					bg.start();
				}
				@Override
				public void onFinish() {					    	 
					//Toast.makeText(getBaseContext(), "xong phim", Toast.LENGTH_SHORT).show();	
					NetworkController.DislayResultVoteKick();
				}
			}.start();
			}
		})
		.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				
			}
		})
		.create();		
		dlg.show();
		
	}
	
	
	
	
	
	public void ShowSetTimeStopTalking(){
		final EditText txtTimeTalk=new EditText(this);
		txtTimeTalk.setSingleLine();
		txtTimeTalk.setInputType(2);
		AlertDialog dlg= new AlertDialog.Builder(this)
		.setTitle("Chọn thời gian buộc ngừng thảo luận")
		.setMessage("Thời gian được tính bằng giây.")
		.setView(txtTimeTalk)
		.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				String StrTime=txtTimeTalk.getText().toString();
				int time=Integer.parseInt(StrTime);
				timeStopTalk=time;
				ipBeingStopTalk=new Address("TRUC@192.168.1.77:"+port);
				NetworkController.GuiYeuCauNgungNoi(ipBeingStopTalk,time);
				Log.d("Phu","vao onclick ngung noi");
				long timeLong=timeStopTalk *1000;
				Toast.makeText(getBaseContext(), timeLong+"", 1).show();
				CountDownTimer timer=new CountDownTimer(timeLong,1000) {
					
					@Override
					public void onTick(long millisUntilFinished) {
						// TODO Auto-generated method stub
						
					}
					
					@Override
					public void onFinish() {
						// TODO Auto-generated method stub
						Toast.makeText(getBaseContext(), "Het gio", 1).show();
						NetworkController.GuiChoPhepNoiChuyen(ipBeingStopTalk);
					}
				}.start();
			}
				
		})
		.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				
			}
		})
		.create();		
		dlg.show();
		
	}
	
	@Override
	public void onStart(){
		super.onStart();
		Log.d("Phu","vao onstart");
		if(NetworkController._peer==null)
		{
			
			Log.d("Phu","vao if activity");
			account=new AccountDTO();
			quyen=new ArrayList<Quyen>();
			Quyen CamNoi=new Quyen(false, false, false, true);
			Quyen Chat=new Quyen(false, false, false, false);
			Quyen Kick=new Quyen(false, false, false, true);
			Quyen Vote=new Quyen(false, false, false, true);
			quyen.add(Chat);
			quyen.add(CamNoi);
			quyen.add(Kick);
			quyen.add(Vote);
			account.setRule(quyen);
			Log.d("Phu","account");
			NetworkController._peer=new NetworkLayer(null, "abc", "TRUC",port , account);
			Log.d("Phu",NetworkController._peer.getAddressPeer());
			this.setTitle(NetworkController._peer.getAddressPeer());
		}
	}
	
	public void Show(String message){
		//Toast.makeText(this, "hehe Xin chao", Toast.LENGTH_SHORT).show();
		AlertDialog dlg= new AlertDialog.Builder(this)
		.setTitle("Thông báo")
		.setMessage(message)
		.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub			
			}
		})
		.create();		
		dlg.show();
	}
	
	
	public void ShowResultVoteKick(final Address toAdd){
		
		if(yesVote.size()>0 || noVote.size()>0){
			String message="Kết quả biểu quyết : ";
			//message+="\n yes : "+yesVote.size();
		//	message+=" no : "+noVote.size()+"\n";
			int sizeALL=yesVote.size()+noVote.size();
			float yesPer=(float)yesVote.size()/sizeALL*100;
			float noPer=(float)noVote.size()/sizeALL*100;
			int yesPercent,noPercent;
			yesPercent=(int)yesPer;
			noPercent=(int)noPer;
		//	message+="\n All: "+sizeALL+ ", yesPer="+yesPercent+", noPer="+noPercent;
			message+=yesPercent+"% đồng ý và "+noPercent+"% không đồng ý.\n";
			if(yesPercent >= noPercent){
				kickVoteResult=1;//bi moi ra khoi nhom
				message+="Kết quả cuối cùng là: YES";
			}
			else{
				kickVoteResult=0;//khong bi moi ra khoi nhom
				message+="Kết quả cuối cùng là: NO";
			}
			message+="\n Gửi kết quả tới các thành viên trong nhóm?";
			AlertDialog dlg= new AlertDialog.Builder(this)
			.setTitle("Thông báo kết quả biểu quyết")
			.setMessage(message)
			.setPositiveButton("OK", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub		
					NetworkController.ShowMessageNotice("ket qua "+kickVoteResult);
					NetworkController.SendResultVoteKickMember(new Address("TRUC@192.168.1.99:8080"), kickVoteResult, ipBeingKick);
					NetworkController.SendResultVoteKickMember(new Address("TRUC@192.168.1.88:8080"), kickVoteResult, ipBeingKick);
					NetworkController.SendResultVoteKickMember(new Address("TRUC@192.168.1.77:8080"), kickVoteResult, ipBeingKick);
				}
			})
			.setNegativeButton("NO", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub		
					
				}
			})
			.create();		
			dlg.show();
		}
		else{
			NetworkController.ShowMessageNotice("Không có ai tham gia biểu quyết.");
			NetworkController.SendResultVoteKickMember(new Address(ipBeingKick), kickVoteResult, ipBeingKick);
		}
	}
	
	public void CapNhatListChat(String mess,String add){
		String s=listChat.getText().toString();
		s+="\n"+add+" :"+mess;
		//s+=NetworkController._peer.getAccount().getRule().get(0).getSend();
		listChat.setText(s);
		
	}
	
	public void HienThiMHBieuQuyetKick(){
		
		Intent i=new Intent(this.getBaseContext(),frmBieuQuyetMoiRoiNhom.class);
		startActivity(i);
	}
	//tao lao
	public void showFrm1(){
		Intent i=new Intent(getBaseContext(), HelloForm1.class);
		startActivity(i);
	}
	
	//hàm thống kê kết quả phản hồi
	public int ThongKeKetQuaBieuQuyetKick(){
		int kq=-1; 
		int sizeALL=yesVote.size()+noVote.size();
		int yesPercent=yesVote.size()/sizeALL*100;
		int noPercent=noVote.size()/sizeALL*100;
		if(yesPercent >= noPercent){
			kq=1;//bi moi ra khoi nhom
			
		}
		else{
			kq=0;//khong bi moi ra khoi nhom
			
		}
			return kq;
	}
	
	
	public void finishActivity(){
		finish();
	}
}
